import { useState } from "react"
import { useSelector } from "react-redux"
import { changeSbujectApi, getAllSubjectsApi } from '@/http/api'
import { Button, Dialog, Popup } from 'antd-mobile'
export default function Subjects() {
    const [state, setState] = useState<Exam[]>([])
    const [show, setShow] = useState(false)
    const [code, setCode] = useState('')
    const getSubjects = () => {
        setShow(true)
        let subjects = sessionStorage.getItem('subjects')
        // 先判断有没有缓存 ，如果没有，就发请求
        if (!subjects) {
            getAllSubjectsApi().then(res => {
                if (res.errCode === 0) {
                    setState(res.data)
                    // 请求回来，要把数据缓存起来
                    sessionStorage.setItem('subjects', JSON.stringify(res.data))
                }
            })
        } else {
            // 如果有，就从缓存里面取就行
            setState(JSON.parse(subjects) as Exam[])
        }
    }

    const selectSbujects = (title: string, actionCode: string) => {
        setShow(false)
        setSubName(title)
        setCode(actionCode)
    }

    const name = useSelector((state: RootState) => state.user.subjectName);
    const [subName, setSubName] = useState(name)

    const sureFn = () => {
        // 弹出一个确认框
        Dialog.confirm({
            content: `确定要设置${subName}为默认学科吗？`,
            cancelText: '取消',
            confirmText: '确定',
            onCancel: () => {
                // console.log('取消')
            },
            onConfirm: () => {
                // console.log('确定')
                // 发请求，然后在成功后，跳转回首页
                changeSbujectApi(code).then(res => {
                    if (res.errCode === 0) {
                        // navigate('/home') // 因为要注意修改学科和渲染首页数据的先后
                    }
                })
            }
        })

        // 确认框点击确定 - 向服务器发请求，把默认学科修改
    }
    return <>
        <div>
            <div className="info">首页显示: {name}</div>
        </div>
        <h2 onClick={getSubjects}>{subName}</h2>
        <Popup
            visible={show}
            position='left'
            onMaskClick={() => {
                setShow(false)
            }}
            onClose={() => {
                setShow(false)
            }}

        >
            {
                state.map(item => <div onClick={() => selectSbujects(item.title, item.actionCode)}>{item.title}</div>)
            }
        </Popup>
        <div>
            <Button onClick={sureFn}>确定</Button>
        </div>
    </>
}